我們在一開始介紹單例,假如我們的 App 需要取得會員相關資料,再做事情,例如呼叫 API 什麼的,所以就像以下程式碼
Member member = new Member();
member.setName("AndyAWD");
member.setAge("18");
member.setAddress("Kaohsiung");
member.setPoint("9527");
//對會員資料做事情
但如果某天你沒睡好,把程式碼做了一些修改
Member member = new Member();
member.setName("AndyAWD");
//對會員資料做事情
member.setAge("18");
member.setAddress("Kaohsiung");
member.setPoint("9527");
所以年齡、地址、點數還沒寫入就做事情,這樣就麻煩了,所以我們需要創造者模式(Builder),一次把該寫入的都寫入,中途也不會被插入
Member member = new Member
.Builder()
.setName("AndyAWD")
.setAge("18")
.setAddress("Kaohsiung")
.setPoint("9527")
.build();
//對會員資料做事情
public class Member {
public static class Builder {
}
}
public class Member {
public Member(Builder builder) {
}
public static class Builder {
}
}
public class Member {
private String name;
public Member(Builder builder) {
this.name = builder.name;
}
public static class Builder {
private String name;
public Builder setName(String name) {
this.name = name;
return this;
}
}
}
public class Member {
private String name;
private String age;
public Member(Builder builder) {
this.name = builder.name;
this.age = builder.age;
}
public static class Builder {
private String name;
private String age;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(String age) {
this.age = age;
return this;
}
}
}